#include <iostream>
#include "RingQueue.hpp"
#include <pthread.h>
#include <unistd.h>

int count = 1;
int threadCount = 5;

struct threadData
{
    RingQueue<int>* bqueue;
    std::string name;
};

void* consumer(void* args)
{
    threadData* td = static_cast<threadData*>(args);

    while (true)
    {
        td->bqueue->push(count);
        // std::cout << td->name << " 生产了一个商品，编号: " << count << std::endl;
        
        sleep(1);
    }

    delete static_cast<threadData*>(args);

    return nullptr;
}

void* producer(void* args)
{
    threadData* td = static_cast<threadData*>(args);

    while (true)
    {
        int data = td->bqueue->pop();
        // std::cout << td->name << " 消费了一个商品，编号: " << data << std::endl;

        sleep(1);
    }

    delete static_cast<threadData*>(args);

    return nullptr;
}

void test()
{
    RingQueue<int>* queue = new RingQueue<int>(30);
    pthread_t tc[threadCount];
    pthread_t tp[threadCount];
    for (int i = 0; i < threadCount; ++i)
    {
        threadData* cptr = new threadData();
        threadData* pptr = new threadData();

        cptr->bqueue = queue;
        pptr->bqueue = queue;
        
        cptr->name = "thread - " + std::to_string(i + 1);
        pptr->name = "thread - " + std::to_string(i + 1 + threadCount);
        
        pthread_create(&tc[i], nullptr, consumer, (void*)cptr);
        pthread_create(&tp[i], nullptr, producer, (void*)pptr);
    }

    for (int i = 0; i < threadCount; ++i)
    {
        pthread_join(tc[i], nullptr);
        pthread_join(tp[i], nullptr);
    }
}

int main()
{
    test();
    
    return 0;
}